import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Row, Col } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, TeamOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'

// 引入API
import { listInterviews, createInterview, getInterview, updateInterview, deleteInterview } from '../../../api/interview'

const { confirm } = Modal

const Interview = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentInterview, setCurrentInterview] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewInterview, setViewInterview] = useState(null)

    // 搜索关键词
    const [searchKeyword, setSearchKeyword] = useState('')

    useEffect(() => {
        fetchInterviews()
    }, [pagination.current, pagination.pageSize, searchKeyword])

    // 获取面试数据
    const fetchInterviews = async () => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize,
                keyword: searchKeyword
            }
            const response = await listInterviews(params)
            setDataSource(response.data || [])
            setPagination({
                ...pagination,
                total: response.total || 0
            })
        } catch (error) {
            console.error('获取面试列表失败:', error)
            message.error('获取面试列表失败')
        } finally {
            setLoading(false)
        }
    }

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = (value) => {
        setSearchKeyword(value)
    }

    // 添加面试
    const handleAdd = () => {
        setCurrentInterview(null)
        setVisible(true)
    }

    // 编辑面试
    const handleEdit = async (record) => {
        try {
            setLoading(true)
            // 获取最新的面试详情
            const response = await getInterview(record.id)
            setCurrentInterview(response.data)
            setVisible(true)
        } catch (error) {
            console.error('获取面试详情失败:', error)
            message.error('获取面试详情失败')
        } finally {
            setLoading(false)
        }
    }

    // 查看面试详情
    const handleView = async (record) => {
        try {
            setLoading(true)
            // 获取最新的面试详情
            const response = await getInterview(record.id)
            setViewInterview(response.data)
            setViewVisible(true)
        } catch (error) {
            console.error('获取面试详情失败:', error)
            message.error('获取面试详情失败')
        } finally {
            setLoading(false)
        }
    }

    // 删除面试
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这条面试记录吗？此操作不可恢复。',
            onOk: async () => {
                try {
                    setLoading(true)
                    await deleteInterview(id)
                    message.success('删除成功')
                    // 重新获取列表数据
                    fetchInterviews()
                } catch (error) {
                    console.error('删除面试失败:', error)
                    message.error('删除面试失败')
                } finally {
                    setLoading(false)
                }
            }
        })
    }

    // 表单提交
    const handleFormSubmit = async (values) => {
        try {
            setLoading(true)
            if (currentInterview) {
                // 编辑面试
                await updateInterview(currentInterview.id, values)
                message.success('编辑成功')
            } else {
                // 添加面试
                await createInterview(values)
                message.success('添加成功')
            }
            // 关闭模态框
            setVisible(false)
            // 重新获取列表数据
            fetchInterviews()
        } catch (error) {
            console.error('保存面试失败:', error)
            message.error('保存面试失败')
        } finally {
            setLoading(false)
        }
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '候选人',
            dataIndex: 'candidateName',
            key: 'candidateName',
            render: (text, record) => (
                <a onClick={() => handleView(record)}>{text}</a>
            )
        },
        {
            title: '应聘职位',
            dataIndex: 'position',
            key: 'position'
        },
        {
            title: '所属部门',
            dataIndex: 'department',
            key: 'department'
        },
        {
            title: '面试时间',
            dataIndex: 'interviewTime',
            key: 'interviewTime'
        },
        {
            title: '时长(分钟)',
            dataIndex: 'duration',
            key: 'duration'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                let color = 'blue'
                if (text === '已完成') color = 'green'
                if (text === '已取消') color = 'volcano'
                if (text === '已安排') color = 'orange'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '结果',
            dataIndex: 'result',
            key: 'result',
            render: (text) => {
                if (text === '待定') return <Tag color="blue">{text}</Tag>
                if (text === '通过') return <Tag color="green">{text}</Tag>
                if (text === '未通过') return <Tag color="red">{text}</Tag>
                return text
            }
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="interview-container">
            <Card title="面试管理" extra={
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    添加面试
                </Button>
            }>
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchInterviews}
                    searchPlaceholder="搜索候选人/职位/部门"
                />
            </Card>

            {/* 面试表单模态框 */}
            <Modal
                title={currentInterview ? '编辑面试' : '添加面试'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentInterview}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name="candidateName"
                        label="候选人"
                        rules={[{ required: true, message: '请输入候选人姓名' }]}
                    >
                        <input placeholder="请输入候选人姓名" />
                    </Form.Item>
                    <Form.Item
                        name="resumeId"
                        label="简历ID"
                        rules={[{ required: true, message: '请输入简历ID' }]}
                    >
                        <input type="number" placeholder="请输入简历ID" />
                    </Form.Item>
                    <Form.Item
                        name="position"
                        label="应聘职位"
                        rules={[{ required: true, message: '请输入应聘职位' }]}
                    >
                        <input placeholder="请输入应聘职位" />
                    </Form.Item>
                    <Form.Item
                        name="department"
                        label="所属部门"
                        rules={[{ required: true, message: '请选择所属部门' }]}
                    >
                        <select>
                            <option value="人事部">人事部</option>
                            <option value="技术部">技术部</option>
                            <option value="市场部">市场部</option>
                            <option value="财务部">财务部</option>
                            <option value="管理部">管理部</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="interviewTime"
                        label="面试时间"
                        rules={[{ required: true, message: '请选择面试时间' }]}
                    >
                        <input type="datetime-local" />
                    </Form.Item>
                    <Form.Item
                        name="duration"
                        label="时长(分钟)"
                        rules={[{ required: true, message: '请输入面试时长' }]}
                    >
                        <input type="number" placeholder="请输入面试时长(分钟)" />
                    </Form.Item>
                    <Form.Item
                        name="location"
                        label="面试地点"
                        rules={[{ required: true, message: '请输入面试地点' }]}
                    >
                        <input placeholder="请输入面试地点" />
                    </Form.Item>
                    <Form.Item
                        name="interviewers"
                        label="面试官"
                        rules={[{ required: true, message: '请输入面试官' }]}
                    >
                        <input placeholder="请输入面试官，多个面试官用逗号分隔" />
                    </Form.Item>
                    <Form.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <select>
                            <option value="已安排">已安排</option>
                            <option value="已完成">已完成</option>
                            <option value="已取消">已取消</option>
                            <option value="已推迟">已推迟</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="result"
                        label="结果"
                        rules={[{ required: true, message: '请选择结果' }]}
                    >
                        <select>
                            <option value="待定">待定</option>
                            <option value="通过">通过</option>
                            <option value="未通过">未通过</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="feedback"
                        label="面试反馈"
                    >
                        <textarea placeholder="请输入面试反馈" rows={4} />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 面试详情模态框 */}
            <Modal
                title="面试详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={null}
                width={700}
            >
                {viewInterview && (
                    <div className="interview-detail">
                        <Row gutter={[16, 16]}>
                            <Col span={24}>
                                <Tabs defaultActiveKey="1">
                                    <Tabs.TabPane tab="基本信息" key="1">
                                        <Descriptions bordered column={2}>
                                            <Descriptions.Item label="ID">{viewInterview.id}</Descriptions.Item>
                                            <Descriptions.Item label="候选人">{viewInterview.candidateName}</Descriptions.Item>
                                            <Descriptions.Item label="简历ID">{viewInterview.resumeId}</Descriptions.Item>
                                            <Descriptions.Item label="应聘职位">{viewInterview.position}</Descriptions.Item>
                                            <Descriptions.Item label="所属部门">{viewInterview.department}</Descriptions.Item>
                                            <Descriptions.Item label="面试时间">{viewInterview.interviewTime}</Descriptions.Item>
                                            <Descriptions.Item label="时长">{viewInterview.duration}分钟</Descriptions.Item>
                                            <Descriptions.Item label="面试地点">{viewInterview.location}</Descriptions.Item>
                                            <Descriptions.Item label="面试官">{viewInterview.interviewers}</Descriptions.Item>
                                            <Descriptions.Item label="状态">
                                                <Tag color={
                                                    viewInterview.status === '已完成' ? 'green' : 
                                                    (viewInterview.status === '已取消' ? 'volcano' : 
                                                    (viewInterview.status === '已安排' ? 'orange' : 'blue'))
                                                }>
                                                    {viewInterview.status}
                                                </Tag>
                                            </Descriptions.Item>
                                            <Descriptions.Item label="结果">
                                                {viewInterview.result === '待定' ? <Tag color="blue">{viewInterview.result}</Tag> :
                                                viewInterview.result === '通过' ? <Tag color="green">{viewInterview.result}</Tag> :
                                                viewInterview.result === '未通过' ? <Tag color="red">{viewInterview.result}</Tag> :
                                                viewInterview.result}
                                            </Descriptions.Item>
                                        </Descriptions>
                                    </Tabs.TabPane>
                                    <Tabs.TabPane tab="面试反馈" key="2">
                                        <div style={{ padding: '16px', whiteSpace: 'pre-line' }}>
                                            {viewInterview.feedback || '暂无面试反馈'}
                                        </div>
                                    </Tabs.TabPane>
                                </Tabs>
                            </Col>
                        </Row>
                    </div>
                )}
            </Modal>
        </div>
    )
}

export default Interview